package com.atguigu.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excel.SubjectData;
import com.atguigu.eduservice.entity.subject.OneSubject;
import com.atguigu.eduservice.entity.subject.TwoSubject;
import com.atguigu.eduservice.listener.SubjectExcelListener;
import com.atguigu.eduservice.mapper.EduSubjectMapper;
import com.atguigu.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author shaki
 * @since 2021-05-30
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Override
    public void saveSubject(MultipartFile file, EduSubjectService subjectService) {
        String filename = file.getOriginalFilename();
        try{
            InputStream in = file.getInputStream();
            EasyExcel.read(in, SubjectData.class, new SubjectExcelListener(subjectService)).sheet().doRead();
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    @Override
    public List<OneSubject> getAllOneTwoSubject() {
        //查询所有的一级分类
        QueryWrapper<EduSubject> wrapperOne = new QueryWrapper<>();
        wrapperOne.eq("parent_id","0");
        List<EduSubject> oneSubjectList = baseMapper.selectList(wrapperOne);
        //查询所有的二级分类
        QueryWrapper<EduSubject> wrapperTwo = new QueryWrapper<>();
        wrapperTwo.ne("parent_id","0");
        List<EduSubject> twoSubjectList = baseMapper.selectList(wrapperTwo);
        //创建集合，用于存储最终封装数据
        List<OneSubject> finalSubjectList = new ArrayList<>();
        //封装一级分类
        for (EduSubject oneSubject : oneSubjectList) {
            OneSubject subject1 = new OneSubject();
            //oneSubject.setId(subject.getId());
            //oneSubject.setTitle(subject.getTitle());
            BeanUtils.copyProperties(oneSubject, subject1); //工具类简化过程
            finalSubjectList.add(subject1);
            //封装二级分类
            List<TwoSubject> twoFinalSubjectList = new ArrayList<>();
            for (EduSubject twoSubject : twoSubjectList) {
                if(oneSubject.getId().equals(twoSubject.getParentId())){
                    TwoSubject subject2 = new TwoSubject();
                    BeanUtils.copyProperties(twoSubject, subject2); //工具类简化过程
                    twoFinalSubjectList.add(subject2);
                }
            }
            subject1.setChildren(twoFinalSubjectList);
        }

        return finalSubjectList;
    }
}
